﻿using DDD.Common.Extensions;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace DDD.Common.Services;

public class JwtTokenService
{
    public string Create(JwtOption option)
    {
        if (option == null)
            throw new ArgumentNullException(nameof(option));

        List<Claim> customClaims = new List<Claim>();
        if (option.Claims != null && option.Claims.Any())
            customClaims.AddRange(option.Claims);

        var serectKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(option.Serect));
        var credential = new SigningCredentials(serectKey, SecurityAlgorithms.HmacSha256);

        var jwtToken = new JwtSecurityToken(
            option.Issure,
            option.Audiance,
                customClaims,
                DateTime.Now,
                DateTime.Now.AddMinutes(option.ExpireMinute),
                credential);

        return new JwtSecurityTokenHandler().WriteToken(jwtToken);
    }

    public DateTime GetExpireTime(string token)
    {
        if (string.IsNullOrEmpty(token))
            throw new ArgumentNullException(nameof(token));

        return new JwtSecurityTokenHandler().ReadJwtToken(token!).Payload[JwtRegisteredClaimNames.Exp].GetTimeSpanToDate();
    }
}

public record JwtOption
{
    public List<Claim> Claims { get; init; }

    public string Audiance { get; init; }

    public string Issure { get; init; }

    public double ExpireMinute { get; init; }

    public string Serect { get; init; }
}
